package com.sangmo.fts.clazz.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.fts.clazz.model.Clazz;
import com.sangmo.fts.external.response.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;

@Service
@Transactional
public class ClazzService extends DelegateViewService<Clazz> {

    @Autowired
    private ClazzEntityService clazzEntityService;

    @Override
    protected ViewService<Clazz> getEntityService() {
        return clazzEntityService;
    }


    public Clazz createIfNotExists(LoginInfo.Clazz clazzDto) {
        Clazz clazz = clazzEntityService.findByExClazzId(clazzDto.getId()+"");
        if (null == clazz) {
            Clazz entity = new Clazz();
            entity.setExClazzId(clazzDto.getId()+"");
            entity.setName(clazzDto.getName());
            return this.create(entity);
        }
        return clazz;
    }

    public Clazz findByStudentId(Long userId) {
        Collection<Clazz> clazzes = clazzEntityService.findByUserId(userId);
        if (clazzes.size() > 1) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.student.clazz.associated.one");
        }
        return clazzes.size()==1?(new ArrayList<Clazz>(clazzes)).get(0) : null;
    }

    public Collection<Clazz> findByExaminationId(Long examinationId) {
        return clazzEntityService.findByExaminationId(examinationId);
    }

    public PageResult<Clazz> selection(PageSearch ps) {
        Long currentUserId = (Long) UserSession.getUserInterface().getId();
        return clazzEntityService.searchByUserId(currentUserId, ps);
    }
}
